﻿using UnityEngine;
using System.Collections;

public class Background : MonoBehaviour
{
	public int StartAlpha 		= 5;
	public int NumAlphaCuts		= 10;

	private int m_CurrentAlpha 	= 0;

	public void TargetKilled( Target _Killed )
	{
		if ( _Killed.Alpha < m_CurrentAlpha )
		{
			ChangeAlpha( m_CurrentAlpha + 1 );
		}
		else if ( _Killed.Alpha > m_CurrentAlpha )
		{
			ChangeAlpha( m_CurrentAlpha - 1 );
		}
	}

	// Use this for initialization
	void Start ()
	{
		// Resize so it fits the camera size
		float HeightScale 		= Camera.main.orthographicSize * 2.0f;

		transform.position 		= Vector3.zero;
		transform.localScale 	= new Vector3( HeightScale * Camera.main.aspect, HeightScale, 1.0f );

		// Reposition camera
		Camera.main.transform.position = Vector3.zero;
		Camera.main.transform.rotation = Quaternion.identity;

		// Resize and position collider (center and size is local)
		BoxCollider2D ColliderComp = GetComponent< BoxCollider2D >();
		ColliderComp.center 	= new Vector3( 0.55f, 0.0f, 0.0f );
		ColliderComp.size 		= new Vector3( 0.1f, 1.0f, 1.0f );

		// Change start alpha
		ChangeAlpha( StartAlpha );
	}

	void OnTriggerExit2D( Collider2D _Other )
	{
		Target CurTarget = _Other.GetComponent< Target >();
		if ( CurTarget != null )
		{
			// Change background
			if ( CurTarget.Alpha < m_CurrentAlpha )
			{
				ChangeAlpha( m_CurrentAlpha - 1 );
			}
			else if ( CurTarget.Alpha > m_CurrentAlpha )
			{
				ChangeAlpha( m_CurrentAlpha + 1 );			
			}
		}

		Destroy( _Other.gameObject );
	}

	void ChangeAlpha( int _NewAlpha )
	{
		m_CurrentAlpha 			= Mathf.Clamp( _NewAlpha, 0, NumAlphaCuts );

		float NewGrey			= (float)m_CurrentAlpha / (float)NumAlphaCuts;

		SpriteRenderer SpriteComp = GetComponent< SpriteRenderer >();
		SpriteComp.color 		= new Color( NewGrey, NewGrey, NewGrey );
	}
}
